﻿using ERP.EquipmentManage.Dtos;
using ERP.ERPModels.EquipmentManage;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace ERP.EquipmentManage
{
    /// <summary>
    /// 设备点检保养项目服务实现
    /// </summary>
    public class DvsubjectService : ApplicationService, IDvsubjectService
    {
        private readonly IRepository<Dvsubject, int> _dvsubjectRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dvsubjectRepository">仓储</param>
        public DvsubjectService(IRepository<Dvsubject, int> dvsubjectRepository)
        {
            _dvsubjectRepository = dvsubjectRepository;
        }

        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="input">创建信息</param>
        /// <returns>创建后的信息</returns>
        public async Task<DvsubjectDto> CreateAsync(CreateDvsubjectDto input)
        {
            // 检查编码是否重复
            var existItem = await _dvsubjectRepository.FirstOrDefaultAsync(x => x.Subcode == input.Subcode);
            if (existItem != null)
            {
                throw new Exception("项目编码已存在");
            }

            var dvsubject = new Dvsubject
            {
                Subcode = input.Subcode,
                Subname = input.Subname,
                Subtype = input.Subtype,
                Isdel = input.Isdel,
                Subcontext = input.Subcontext,
                Subarea = input.Subarea
            };

            await _dvsubjectRepository.InsertAsync(dvsubject);
            await CurrentUnitOfWork.SaveChangesAsync();

            return ObjectMapper.Map<Dvsubject, DvsubjectDto>(dvsubject);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id">ID</param>
        public async Task DeleteAsync(int id)
        {
            await _dvsubjectRepository.DeleteAsync(id);
            await CurrentUnitOfWork.SaveChangesAsync();
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="ids">ID列表</param>
        public async Task BatchDeleteAsync(List<int> ids)
        {
            if (ids == null || ids.Count == 0)
            {
                throw new ArgumentException("删除的ID列表不能为空");
            }

            // 批量删除
            var query = await _dvsubjectRepository.GetQueryableAsync();
            var itemsToDelete = await query.Where(x => ids.Contains(x.Id)).ToListAsync();
            
            if (itemsToDelete.Any())
            {
                await _dvsubjectRepository.DeleteManyAsync(itemsToDelete);
                await CurrentUnitOfWork.SaveChangesAsync();
            }
        }

        /// <summary>
        /// 根据ID获取
        /// </summary>
        /// <param name="id">ID</param>
        /// <returns>项目详情</returns>
        public async Task<DvsubjectDto> GetByIdAsync(int id)
        {
            var dvsubject = await _dvsubjectRepository.GetAsync(id);
            return ObjectMapper.Map<Dvsubject, DvsubjectDto>(dvsubject);
        }

        /// <summary>
        /// 获取分页列表
        /// </summary>
        /// <param name="input">查询条件</param>
        /// <returns>分页结果</returns>
        public async Task<PagedResultDto<DvsubjectDto>> GetPagedListAsync(GetDvsubjectInputDto input)
        {
            // 构建查询
            var query = await _dvsubjectRepository.GetQueryableAsync();

            // 应用筛选条件
            if (!string.IsNullOrWhiteSpace(input.Subcode))
            {
                query = query.Where(x => x.Subcode.Contains(input.Subcode));
            }

            if (!string.IsNullOrWhiteSpace(input.Subname))
            {
                query = query.Where(x => x.Subname.Contains(input.Subname));
            }

            if (!string.IsNullOrWhiteSpace(input.Subtype))
            {
                query = query.Where(x => x.Subtype == input.Subtype);
            }

            // 计算总数
            var totalCount = await query.CountAsync();

            // 分页查询
            var items = await query
                .OrderBy(x => x.Subcode)
                .Skip((input.PageIndex - 1) * input.PageSize)
                .Take(input.PageSize)
                .ToListAsync();

            // 映射为DTO
            var dtos = ObjectMapper.Map<List<Dvsubject>, List<DvsubjectDto>>(items);

            return new PagedResultDto<DvsubjectDto>(totalCount, dtos);
        }

        /// <summary>
        /// 获取项目类型列表
        /// </summary>
        /// <returns>类型列表</returns>
        public async Task<List<string>> GetSubtypeListAsync()
        {
            var query = await _dvsubjectRepository.GetQueryableAsync();
            var types = await query
                .Select(x => x.Subtype)
                .Distinct()
                .OrderBy(x => x)
                .ToListAsync();

            return types;
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="id">ID</param>
        /// <param name="input">更新信息</param>
        /// <returns>更新后的信息</returns>
        public async Task<DvsubjectDto> UpdateAsync(int id, UpdateDvsubjectDto input)
        {
            // 检查编码是否重复
            var existItem = await _dvsubjectRepository.FirstOrDefaultAsync(x => x.Subcode == input.Subcode && x.Id != id);
            if (existItem != null)
            {
                throw new Exception("项目编码已存在");
            }

            var dvsubject = await _dvsubjectRepository.GetAsync(id);
            
            dvsubject.Subcode = input.Subcode;
            dvsubject.Subname = input.Subname;
            dvsubject.Subtype = input.Subtype;
            dvsubject.Isdel = input.Isdel;
            dvsubject.Subcontext = input.Subcontext;
            dvsubject.Subarea = input.Subarea;

            await _dvsubjectRepository.UpdateAsync(dvsubject);
            await CurrentUnitOfWork.SaveChangesAsync();

            return ObjectMapper.Map<Dvsubject, DvsubjectDto>(dvsubject);
        }

        /// <summary>
        /// 导出选定的数据
        /// </summary>
        /// <param name="ids">选定的ID列表</param>
        /// <returns>选定的数据列表</returns>
        public async Task<List<DvsubjectDto>> ExportSelectedAsync(List<int> ids)
        {
            // 获取选定ID的数据
            var query = await _dvsubjectRepository.GetQueryableAsync();
            var items = await query
                .Where(x => ids.Contains(x.Id))
                .OrderBy(x => x.Subcode)
                .ToListAsync();

            // 映射为DTO
            var dtos = ObjectMapper.Map<List<Dvsubject>, List<DvsubjectDto>>(items);
            return dtos;
        }
    }
}
